<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>弹幕</title>
    <style>
        .main{
            width: 800px;
            margin: auto;
            height: 600px;
            background-color: black;
            overflow: hidden;
        }
        .item {
            background-color: brown;
            color: aliceblue;
            margin-top: 20px;
            margin-left: 100px;
            height: 25px;
            max-width: 600px;
            overflow: hidden;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
    <div class="main" id="main">
       <!--
        <div v="700" class="item" style="color: aliceblue; margin-top: 20px; margin-left: 100px; float: left">测试123121333333333333333333333333</div>
    -->
    </div>
    <div style="margin: auto">
        <input type="text" id="input_1">
        <button id="send_btn">发送</button>
    </div>
    <button id="startBtn">start</button>

<script>
    let ws = null;
    let margin_left = 800;
    let margin_top = 20;
    function start(){
        window.setInterval(function (){
            $("#main").children("div").each(function () {
                let v = $(this).attr("v");
                v -= 1;
                $(this).attr("v", v);
                $(this).css("margin-left", v+"px");
                if(v < 0){
                    $(this).remove();
                }
            });
        },50);
        if(ws != null){
            return;
        }
        ws = new WebSocket("ws://localhost:8010/ws");
        ws.onopen = function(){
            console.log("打开连接");
            //ws.send("ddd"); // 发送消息
        };

        ws.onmessage = function(evt) { // 接收服务器消息
            let item = " <div v = '700' class='item' style=\"color: aliceblue; margin-top: "+margin_top+"px; margin-left: "+margin_left+"px; float: left\">"+evt.data+"</div>";
            $("#main").append(item);
            top += 20;
            if(top > 600){
                top = 20;
            }

        };

        ws.onclose = function(evt) {
            console.log("连接关闭"); // 关闭连接
            ws = null;
        };

        ws.onerror = function(evt) {
            console.log("连接异常:",evt); // 连接异常
            ws = null;
        };
    }
    $("#startBtn").click(start)

    $("#send_btn").click(function () {
        let text = $("#input_1").val();
        if(text){
            ws.send(text);
        }
    });
</script>
</body>
</html>